import { END, HEAD } from "./proto";
import { CodecType } from "./types";

// type seq cmd 

export class Frame {

    buf: number[];

    constructor(buf: number[] = []) {
        this.buf = buf;
    }

    static readonly MINI_LEN = 5;

    static make = (...args: CodecType[]) => {
        let len = 0;
        for (const arg of args) {
            len += arg.size();
        }
        const buf = new Array<number>(len + 5);
        buf[0] = (HEAD >> 8) & 0xFF;
        buf[1] = HEAD & 0xFF;
        buf[2] = len & 0xFF;
        let index = 3;
        for (const arg of args) {
            arg.encode(buf, index);
            index += arg.size();
        }
        let sum = 0;
        for (let i = 0; i < len; i ++) {
            sum ^= buf[i + 3];
        }
        buf[3 + len] = sum & 0xFF;
        buf[4 + len] = END;
        return buf;
    }

    type = () => {
        return this.buf[0];
    }

    seq = () => {
        return this.buf[1];
    }

    cmd = () => {
        return this.buf[2];
    }

    parse = (...args: CodecType[]) => {
        let index = 3;
        const max = this.buf.length - 2;
        for (const arg of args) {
            if (index >= max) {
                throw '数据长度错误';
            }
            arg.decode(this.buf, index);
            index += arg.size();
        }
    }
}

